package system;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import system.sqlOperation;


@WebServlet("/addSubject")
public class addSubject extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	
    	String userid = req.getParameter("user_id"); 
    	String subjectid = req.getParameter("subjectid"); 
    	int operate = Integer.parseInt(req.getParameter("operate"));
    	
    	sqlOperation sql=new sqlOperation();
    	
    	String result = "{\"count\":\"";
    	
    	if(operate==1) {
    		int count=sql.getCount("select count(*) from teacher_subject where  teacher_id='"+userid+"'");
    		result = "{\"count\":\""+count+"\""; 
    		String[] ids=new String[count];
    		ids=sql.getQuerySet("select subject_id from teacher_subject where teacher_id='"+userid+"'",count);
    		
    		for(int i=0;i<count;i++) {
    			result+=",\"id"+String.valueOf(i+1)+"\":\""+ids[i]+"\",\"name"+String.valueOf(i+1)+"\":\""+(sql.getQuerySet("select subject_name from subject where subject_id='"+ids[i]+"'", 1))[0]+"\"";
    		}	
    		result +="}";
    	}else if(operate==2) {
    		int count=sql.getCount("select count(*) from subject where subject_id not in(select subject.subject_id from subject,teacher_subject where teacher_subject.teacher_id='"+userid+"' and teacher_subject.subject_id=subject.subject_id)");
    		result = "{\"count\":\""+count+"\""; 
    		String[] ids=new String[count];
    		ids=sql.getQuerySet("select subject.subject_id from subject where subject_id not in(select subject.subject_id from subject,teacher_subject where teacher_subject.teacher_id='"+userid+"' and teacher_subject.subject_id=subject.subject_id)",count);
    		for(int i=0;i<count;i++) {
    			result+=",\"id"+String.valueOf(i+1)+"\":\""+ids[i]+"\",\"name"+String.valueOf(i+1)+"\":\""+(sql.getQuerySet("select subject_name from subject where subject_id='"+ids[i]+"'", 1))[0]+"\"";
    		}
    		result +="}";
    	}else if(operate==3) {
    		int insert=sql.getInsert("insert into teacher_subject values('"+userid+"','"+subjectid+"')");
    		result = "{\"insert\":\""+insert+"\"}"; 
    	}else if(operate==4) {
    		int delete=sql.getDelete("delete from teacher_subject where teacher_id='"+userid+"' and subject_id='"+subjectid+"'");
    		result = "{\"insert\":\""+delete+"\"}";
    	}
    	
    	resp.setContentType("application/json;charset=UTF-8");
    	PrintWriter out = resp.getWriter();		
    	out.write(result);
    	
    }

}
